package com.cg.service;

import com.cg.common.KeyCommon;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CodeServiceImpl
 * @Description TODO
 * @Author CG
 * @Date 2023/12/31 13:21
 **/
public class CodeServiceImpl implements CodeService {


    @Value("${codeTimeOut}")//3分钟
    private Long codeTimeOut;
    @Value("${codeReTimeOut}")//1分钟
    private Long codeReTimeOut;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 保存到redis中
     */
    @Override
    public String createCode(String phone) {
        //生成随机code
        Random random = new Random();
        Integer code = random.nextInt(9000)+1000;
        //生成第一次保存的key，三分钟之内有效
        String key1 = KeyCommon.SMS_PHONE_REGISTER+phone;
        //生成验证的key，1分钟之内有效,1分钟之内不能重复生成
        String key2 = KeyCommon.SMS_PHONE_REGISTER_RE+phone;

        //保存到redis中
        //3分钟
        redisTemplate.opsForValue().set(key1,code.toString(),codeTimeOut, TimeUnit.SECONDS);
        //1分钟
        redisTemplate.opsForValue().set(key2,code.toString(),codeReTimeOut, TimeUnit.SECONDS);

        return code.toString();
    }

    /**
     * 验证code是否已经生成
     */
    @Override
    public Boolean checkCode(String phone, String code) {
        //生成key
        String key1 = KeyCommon.SMS_PHONE_REGISTER+phone;
        //通过key获取value
        String value = redisTemplate.opsForValue().get(key1);
        if(value == null || value.equals("")){
            return false;
        }
        //比较value和code是否相同
        if(code.equals(value)){
            return true;
        }
        return false;
    }

    /**
     * 通过手机号获取验证码
     */
    @Override
    public String getCode(String phone) {
        String key = KeyCommon.SMS_PHONE_REGISTER_RE+phone;
        String value = redisTemplate.opsForValue().get(key);
        return value;
    }

    @Override
    public String getCodeThree(String phone) {
        String key = KeyCommon.SMS_PHONE_REGISTER+phone;
        String value = redisTemplate.opsForValue().get(key);
        return value;
    }
}
